/*
 * @Author: i@douxuefeng.cn
 * @Date: 2024-01-13 13:20:32
 * @LastEditTime: 2024-01-13 13:45:46
 * @LastEditors: i@douxuefeng.cn
 * @Description:
 */
package accessToken

import (
	"encoding/json"
	"fmt"

	"gitee.com/douxuefeng/go-utils/request"
	"gitee.com/douxuefeng/go-utils/wechat/corp/config"
	"gitee.com/douxuefeng/go-utils/wechat/corp/params"
)

type accessToken struct {
	cf *config.CorpConfig
}

const getToken = params.CorpApi + "/gettoken?corpid=%s&corpsecret=%s"

func NewAccessToken(cf *config.CorpConfig) *accessToken {
	return &accessToken{cf}
}

func (a *accessToken) GetAccessToken() (string, error) {
	if a.cf.Cache.IsExist(a.cf.CacheKey) {
		return a.cf.Cache.Get(a.cf.CacheKey)
	}
	url := fmt.Sprintf(getToken, a.cf.CorpId, a.cf.CorpSecret)
	req := request.NewRequest()
	resp, err := req.Get(url)
	if err != nil {
		return "", err
	}
	var res params.GetAccessTokenReply
	err = json.Unmarshal(resp.Body(), &res)
	if err != nil {
		return "", err
	}
	if res.Errcode != 0 {
		return "", fmt.Errorf("get access token error, errcode=%d, errmsg=%s", res.Errcode, res.Errmsg)
	}
	a.cf.Cache.Set(a.cf.CacheKey, res.AccessToken, int64(res.ExpiresIn)-2000)
	return res.AccessToken, nil
}
